python3 使用flask 您所在的位置:网站首页 python3 输出HTML日志 python3 使用flask

python3 使用flask

2024-06-27 05:18| 来源: 网络整理| 查看: 265

使用python3和flask_socketio ,实现服务器上的tail和top命令的实时展示,将结果实时展示在web上

tail在页面上限制了显示长度,自动滚动显示最新数据

效果如下:

tail效果

 

 

 

top效果

 

 

 和Vue配合使用时,可能会出现如下问题

GET http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=M-9xlys 400 (BAD REQUEST) Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=M-9xlys' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

 

 

 

 提示的很明显,就是跨域了,然后理所当然的按平时的解决方式

比如使用flask_cors或者自己利用flask的钩子函数在请求前后,设置请求头等,但是依然会报错!!!

 

正确的解决方式是,在实例化SocketIO时,加上 cors_allowed_origins="*"

socketio = SocketIO(app , cors_allowed_origins="*")

 

 

 

主要代码如下:

# coding=utf-8 import os import re from threading import Lock from flask import Flask, render_template from flask_socketio import SocketIO from config import LOG_FILE, SECRET_KEY app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY socketio = SocketIO(app)# 跨域时使用下面的# socketio = SocketIO(app,cors_allowed_origins="*") close = False thread = None thread_lock = Lock() client_num = 0 # tail页面连入数量 def get_tail_n_info(n): ''' tail按行获取 :param n: 行数 :return: ''' try: tail_pipe = os.popen(f'tail -n {n} {LOG_FILE} ') except: print('文件不存在') return '' else: tail_output = iter(tail_pipe.readlines()) tail_pipe.close() return tail_output def tail_close(): with thread_lock: global close, thread, client_num client_num -= 1 print('有客户端离开tail页面,当前页面客户端剩余数量为', client_num) if client_num = 6: if num == 6: new_line = " " else: new_line = "" td_list = re.split(r" +", line) if len(td_list) > 1: for td in td_list: if td.strip(): new_line += f"{(8-len(td))*';'+td}" new_line += "" else: new_line = '' + line.replace(' ', ";") + '' _html += new_line _html += '' return _html @app.route('/') def index(): return render_template('index.html') @app.route('/tail', methods=['GET']) def tail_html(): return render_template('tail.html') @app.route('/top', methods=['GET']) def top_html(): return render_template('top.html') @socketio.on('connect', namespace="/shell") def connect(): print("connect..") @socketio.on('disconnect', namespace="/shell") def disconnect(): print("disconnect..") @socketio.on('open_tail', namespace="/shell") def open_tail(message): print('received open_tail message: ' + message.get('data', '')) global thread, close, client_num with thread_lock: client_num += 1 print('有客户端进入tail页面,当前页面客户端数量为', client_num) if thread is None: close = False thread = socketio.start_background_task(target=background_thread) else: # 有其他客户端正在使用时,则先发送最近30条过去 for line in get_tail_n_info(n=30): if line.strip(): socketio.emit('tail_response', {'text': line}, namespace='/shell') @socketio.on('close_tail', namespace="/shell") def close_tail(message): print('准备关闭tail', message.get('data', '')) tail_close() @socketio.on('handle_top', namespace="/shell") def handle_top(message): print('received handle_top message: ' + message.get('data', '')) top_info = get_top_info() socketio.emit('top_response', {'text': top_info}, namespace='/shell') def background_thread(): try: tail_pipe = os.popen('tail -f ' + LOG_FILE) except: print('文件不存在') return else: while not close: tail_output = tail_pipe.readline() if tail_output.strip(): socketio.emit('tail_response', {'text': tail_output}, namespace='/shell') tail_pipe.close() if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=8000)

 

DOCTYPE html> $(document).ready(function () { var child_num = 0; var namespace = '/shell'; var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace); socket.on('tail_response', function (res) { if (child_num


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有